//
//  BoatDetialViewController.m
//  WOFishingBoat
//
//  Created by 郑逸凯 on 2018/12/18.
//  Copyright © 2018年 郑逸凯. All rights reserved.
//

#import "BoatDetialViewController.h"
#import <MJRefresh/MJRefresh.h>
#import <Masonry/Masonry.h>
#import "SDCControlView.h"
#import "UIImageView+WoWebCache.h"
#import "HistoryScreenShotModel.h"
#import "CircleButton.h"
#import "YAUserDefault.h"

@interface BoatDetialViewController ()<SDCControlViewDelegate>
@property (nonatomic,strong)UIView *screenShotBackView;
@property (nonatomic,strong)UIImageView *screenShotView;
@property (nonatomic,strong)SDCControlView *controlView;
@property (nonatomic,strong)CircleButton *aroundButton;
@property (nonatomic,strong)CircleButton *resetButton;

@property (nonatomic,strong)BoatInfoModel *boatInfoModel;
@property (nonatomic,strong)RequestSession *controlSDCRequest;
@property (nonatomic,strong)RequestSession *screenShotRequest;
@property (nonatomic,strong)RequestSession *registerMonitorRequest;
@property (nonatomic,strong)RequestSession *releaseMonitorRequest;

@property (nonatomic,strong)NSMutableArray *photos;
@property (nonatomic,assign)BOOL isMonitorRegistered;
@end

@implementation BoatDetialViewController


#pragma mark - Life Cycle

- (instancetype)initWithModel:(BoatInfoModel *)boatInfoModel {
    if (self = [super init]) {
        _boatInfoModel = boatInfoModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = self.boatInfoModel.name;
//    [self.screenShotView wo_setImageWithURL:self.boatInfoModel.imgUrl];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Monitoring.jpeg" ofType:nil];
    self.screenShotView.image = [UIImage imageWithContentsOfFile:path];
    [self setupSubviews];
    [self performLayout];
    
    [self requestRegisterMonitor];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self requestReleaseMonitor];
}


#pragma mark - Public Methods
#pragma mark - Responder Actions


- (void)aroundScreenShotAction {
    [self requestScreenShotNeedAround:YES];
}

- (void)resetDirectionAction {
    [self requestSDCControl:@"home"];
}

#pragma mark - Request
- (void)requestScreenShotNeedAround:(BOOL)needAround {
    if (![self checkStatesAndShowMessage]) {
        return;
    }
    
    NSString *urlStr = WO_PATH_SDC_SCREENSHOT;
    NSDictionary *params = @{
                             @"id":self.boatInfoModel.boatID,
                             @"instruction":(needAround ? @"surround":@"immediate")
                             };
//    @weakify(self);
    [self.screenShotRequest postWithURLString:WO_URL(urlStr) parameters:params completionHandler:^(id responseObject, NSError *error) {
//        @strongify(self);
        if (!error ) {
            [YAToast showTouchableTipMessageInView:@"截图成功，已保存至相册"];
        }else {
            [YAToast showTouchableTipMessageInView:error.domain];
        }
    }];
    
    
}

- (void)requestSDCControl:(NSString *)directionString {
    if (![self checkStatesAndShowMessage]) {
        return;
    }
    NSString *urlStr = WO_PATH_SDC_CTRL;
    NSDictionary *params = @{
                             @"id":self.boatInfoModel.boatID,
                             @"command":@"sdc",
                             @"instruction":directionString
                             };
    //    @weakify(self);
    [self.screenShotRequest postWithURLString:WO_URL(urlStr) parameters:params completionHandler:^(id responseObject, NSError *error) {
        //        @strongify(self);
        if (!error ) {
            [self moveVisualAngleWithDirectionString:directionString];
        }else {
            [YAToast showTouchableTipMessageInView:error.domain];
        }
    }];
}

- (void)requestRegisterMonitor {
    NSString *account = [YAUserDefault ya_objectForKey:KEY_ACCOUNT];
    NSDictionary *params = @{
                             @"id":self.boatInfoModel.boatID,
                             @"username":account,
                             };
    MBProgressHUD *hud = [YAToast showActivityMessageInView:@""];
    @weakify(self);
    [self.releaseMonitorRequest postWithURLString:WO_URL(WO_PATH_MONITOR_REGISTER) parameters:params completionHandler:^(id responseObject, NSError *error) {
        [hud hide:YES];
        @strongify(self);
        if (!error ) {
            self.isMonitorRegistered = YES;
        }else {
            [YAToast showTouchableTipMessageInView:error.domain];
        }
    }];
}

- (void)requestReleaseMonitor {
    NSDictionary *params = @{
                             @"id":self.boatInfoModel.boatID,
                             };
//    MBProgressHUD *hud = [YAToast showActivityMessageInView:@""];
    @weakify(self);
    [self.releaseMonitorRequest postWithURLString:WO_URL(WO_PATH_MONITOR_RELEASE) parameters:params completionHandler:^(id responseObject, NSError *error) {
//        [hud hide:YES];
        @strongify(self);
        if (!error ) {
            self.isMonitorRegistered = YES;
        }else {
            [YAToast showTouchableTipMessageInView:error.domain];
        }
    }];
}



#pragma mark - Delegates
#pragma mark - SDCControlViewDelegate
- (void)SDCControlViewTouched:(SDCControlView *)controlView controlDirection:(SDCControlDirection)controlDirection {
    if (controlDirection == SDCControlScreenShot) {
        [self requestScreenShotNeedAround:NO];
    }else {
         NSString *directionString = [self directionString:controlDirection];
        [self requestSDCControl:directionString];
    }
   
}

#pragma mark - Tableview data source



#pragma mark - Private Methods

- (BOOL)checkStatesAndShowMessage {
    if (self.boatInfoModel.status == 0) {
        [YAToast showTouchableTipMessageInView:@"当前设备离线中，请稍后重试" timer:1];
        return NO;
    }
    if (self.isMonitorRegistered == NO) {
        [YAToast showTouchableTipMessageInView:@"当前设备正在被其他用户监控中，请稍后重试" timer:1];
        return NO;
    }
    return YES;
}

- (void)moveVisualAngleWithDirectionString:(NSString *)directionString {
    CGFloat width = self.screenShotView.frame.size.width;
    CGFloat height = self.screenShotView.frame.size.height;
    CGPoint currentPoint = self.screenShotView.frame.origin;
    CGFloat widthSpace = width/3/10;
    CGFloat heightSpace = height/3/10;
    if ([directionString isEqualToString:@"home"]) {
        currentPoint = CGPointMake(-width/3, -height/3);
    }else if ([directionString isEqualToString:@"up"]) {
        currentPoint.y = currentPoint.y + heightSpace;
    }else if ([directionString isEqualToString:@"down"]) {
        currentPoint.y = currentPoint.y - heightSpace ;
    }else if ([directionString isEqualToString:@"right"]) {
        currentPoint.x = currentPoint.x - widthSpace ;
    }else if ([directionString isEqualToString:@"left"]) {
        currentPoint.x = currentPoint.x + widthSpace ;
    }
    //检查是否越界
    if (currentPoint.y > 0) {
        currentPoint.y = 0;
    }else if (currentPoint.y <  -height/3 * 2) {
        currentPoint.y = -height/3 * 2;
    }
    if (currentPoint.x > 0) {
        currentPoint.x = 0;
    }else if (currentPoint.x <  -width/3 * 2) {
        currentPoint.x = -width/3 * 2;
    }
    
    
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = self.screenShotView.frame;
        frame.origin = currentPoint;
        self.screenShotView.frame = frame;
    }];
}


- (void)setupSubviews {
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.screenShotBackView];
    [self.screenShotBackView addSubview:self.screenShotView];
    [self.view addSubview:self.controlView];
    [self.view addSubview:self.aroundButton];
    [self.view addSubview:self.resetButton];
}

- (void)performLayout {
    [self.screenShotBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.mas_equalTo(Height_TopBar);
        make.height.mas_equalTo(SCREEN_SCALE_VALUE_IN_4_7(211));
    }];
    
    self.screenShotView.frame = CGRectMake(-self.view.frame.size.width, -SCREEN_SCALE_VALUE_IN_4_7(211), self.view.frame.size.width * 3, SCREEN_SCALE_VALUE_IN_4_7(211) * 3);
    
    [self.controlView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.screenShotBackView.mas_bottom).with.offset(25);
        make.centerX.equalTo(self.screenShotBackView);
        make.size.mas_equalTo(CGSizeMake(202, 202));
    }];
    
    [self.aroundButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.controlView.mas_bottom).with.offset(15);
        make.centerX.equalTo(self.controlView).with.offset(-50);
        make.size.mas_equalTo(CGSizeMake(60, 80));
    }];
    
    [self.resetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.aroundButton);
        make.centerX.equalTo(self.controlView).with.offset(50);
        make.size.equalTo(self.aroundButton);
    }];
    
   
}

#pragma mark - Setters and Getters


- (UIImageView *)screenShotView {
    if (!_screenShotView) {
        _screenShotView = [[UIImageView alloc] init];
    }
    return _screenShotView;
}

- (SDCControlView *)controlView {
    if (!_controlView) {
        _controlView = [[SDCControlView alloc] init];
        _controlView.delegate = self;
    }
    return _controlView;
}

- (CircleButton *)aroundButton {
    if (!_aroundButton) {
        _aroundButton = [[CircleButton alloc] initWithImageName:@"mon_ctrl_around" title:@"环绕截图"];
        [_aroundButton addTarget:self action:@selector(aroundScreenShotAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _aroundButton;
}

- (CircleButton *)resetButton {
    if (!_resetButton) {
        _resetButton = [[CircleButton alloc] initWithImageName:@"mon_ctrl_reset" title:@"方向复位"];
        [_resetButton addTarget:self action:@selector(resetDirectionAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _resetButton;
}

- (UIView *)screenShotBackView {
    if (!_screenShotBackView) {
        _screenShotBackView = [[UIView alloc] init];
        _screenShotBackView.clipsToBounds = YES;
    }
    return _screenShotBackView;
}

- (RequestSession *)controlSDCRequest {
    if (!_controlSDCRequest) {
        _controlSDCRequest = [[RequestSession alloc] init];
    }
    return _controlSDCRequest;
}

- (RequestSession *)screenShotRequest {
    if (!_screenShotRequest) {
        _screenShotRequest = [[RequestSession alloc] init];
    }
    return _screenShotRequest;
}

- (RequestSession *)registerMonitorRequest {
    if (!_registerMonitorRequest) {
        _registerMonitorRequest = [[RequestSession alloc] init];
    }
    return _registerMonitorRequest;
}

- (RequestSession *)releaseMonitorRequest {
    if (!_releaseMonitorRequest) {
        _releaseMonitorRequest = [[RequestSession alloc] init];
    }
    return _releaseMonitorRequest;
}

#pragma mark - Helper

- (NSString *)directionString:(SDCControlDirection )controlDirection {
    NSString *directionString = @"home";
    switch (controlDirection) {
        case SDCControlDirectionUp:
            directionString = @"up";
            break;
        case SDCControlDirectionDown:
            directionString = @"down";
            break;
        case SDCControlDirectionLeft:
            directionString = @"left";
            break;
        case SDCControlDirectionRight:
            directionString = @"right";
            break;
            
        default:
            directionString = @"home";
            break;
    }
    return directionString;
}


@end
